const cors = require('@koa/cors'); // 跨域中间件
const koa_body = require('koa-body') // 解析请求体
const path = require('path')
const koajwt = require('koa-jwt') // jwt鉴权

const router = require('../router'); // 路由中间件
const response = require('./response'); // 返回中间件
const error = require('./error'); // 错误处理中间件
const rootDir = process.cwd()

/** 
 * 跨域处理
  */
const mdCors = cors({
  origin: '*',
  credentials: true,
  allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']
});

/**
 * 请求体处理
 */
const mdKoaBody = koa_body({
  multipart: true, // 允许上传多个文件
  formidable: {
    maxFileSize: 800 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
  }
})

const mdStatic = require('koa-static')(path.join(rootDir, './public'))

/**
 * 统一返回格式
 */
const mdResHandler = response();
/**
 * 错误处理
 */
const mdErrorHandler = error();

/**
 * 路由处理
 */
const mdRoute = router.router.routes();
const mdRouterAllowed = router.router.allowedMethods();

const mdJwtRoute = router.jwtRouter.routes();
const mdJwtRouterAllowed = router.jwtRouter.allowedMethods();

/**
 * jwt
 */
const mdJwt = koajwt({
  secret: 'biluo_koa'
}).unless({
  // method: 'GET'
});

module.exports = [
  mdStatic,
  mdKoaBody,
  mdCors,
  mdResHandler,
  mdErrorHandler,
  mdRoute,
  mdRouterAllowed,
  mdJwt,
  mdJwtRoute,
  mdJwtRouterAllowed,
];